package com.zl.learning.json.gson;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

public class PageDataParser implements JsonDeserializer<PageData> {

    @Override
    public PageData<ClassRoom> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        Gson gson = new GsonBuilder().registerTypeAdapter(ClassRoom.class, new ClassRoomParser()).create();
        JsonObject jsonObject = json.getAsJsonObject();
        PageData<ClassRoom> pageData = gson.fromJson(json, PageData.class);
        if (jsonObject.get("page_num") != null) {
            pageData.setPageNum(jsonObject.get("page_num").getAsInt());
        }
        if (jsonObject.get("page_size") != null) {
            pageData.setPageSize(jsonObject.get("page_size").getAsInt());
        }
        if (jsonObject.get("result") != null) {
            List<ClassRoom> albumPhotoList = gson.fromJson(jsonObject.get("result"), new TypeToken<List<ClassRoom>>() {
            }.getType());
            pageData.setResults(albumPhotoList);
        }
        return pageData;
    }


}
